/*
 * NetUtil.h
 *
 *  Created on: 2012-12-14
 *      Author: yangentao@gmail.com
 */

#pragma once;
#include <WinSock2.h>
#include <Windows.h>
#include <string>
#include "SocketOption.h"
#include "SocketError.h"
#include "../AutoLock.h"

using namespace std;

#define throw_socket_error_if(condition)    if (condition) {SocketError e;e.print();throw e;}
#define throw_socket_error()   {SocketError e;e.print();throw e;}

namespace yet {

class SockLib : public ThreadLock{
public:
	SockLib();
	virtual ~SockLib();
public:
	void init();
	void clean();
};

class AutoSockLib{
public:
	AutoSockLib();
	virtual ~AutoSockLib();
private:
	SockLib socklib;
};

string getSocketErrorCodeName(int code);

class FdSet {
public:
	FdSet();
	FdSet(SOCKET s);
	virtual ~FdSet();
public:
	void zero();
	void set(SOCKET s);
	bool isSet(SOCKET s);
	void remove(SOCKET s);
public:
	fd_set fdset;
};

class InetAddr {
public:
	InetAddr();
	InetAddr(u_short port);
	InetAddr(string host, u_short port);
	InetAddr(u_long ip, u_short port);
public:
	void setHost(string host);
	void setIp(string host);
	void setIp(u_long ip);
	void setIpBroadcast();
	string getIP();
	u_long getIpLong();
	bool isEmptyIp();
public:
	void setPort(u_short port);
	void setPortAny();
	short getPort();
public:
	struct sockaddr* getAddr();
	int getSize();
public:
	sockaddr_in addr_in;
};

u_long getIp4(string hostname);

void throwSocketError();
void throwSocketError(int code);
void throwSocketErrorIf(bool cond);

} /* namespace yet */
